package com.linkdood.app.web.rest;

import com.linkdood.app.constants.MenuCode;
import com.linkdood.app.constants.MenuConstants;
import com.linkdood.app.domain.SysMenu;
import com.linkdood.app.exception.GeneralException;
import com.linkdood.app.service.AccountService;
import com.linkdood.app.service.SysMenuService;
import com.linkdood.app.service.SysRoleMenuService;
import com.linkdood.app.utils.StringUtils;
import com.linkdood.app.web.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 菜单管理
 *
 * @author chenkexu
 * @date 2021/4/15
 */
@Slf4j
@RestController
@RequestMapping("/api/menu")
public class SysMenuResource extends BaseController {

    private final SysMenuService sysMenuService;
    private final AccountService accountService;
    private final SysRoleMenuService sysRoleMenuService;

    public SysMenuResource(SysMenuService sysMenuService,
                           AccountService accountService,
                           SysRoleMenuService sysRoleMenuService) {
        this.sysMenuService = sysMenuService;
        this.accountService = accountService;
        this.sysRoleMenuService = sysRoleMenuService;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        List<SysMenu> menus = sysMenuService.listMenuTreeByUserId(accountService.getCurrentAccountId());
        return AjaxResult.success(sysMenuService.buildMenus(menus));
    }

    /**
     * 获取菜单列表
     */
    @PreAuthorize("@ss.hasPermi('bxy:menu:index')")
    @GetMapping
    public AjaxResult list(SysMenu menu) {
        // FIXME(gaoliusheng) 确认无用代码需要删除而不是注释
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = sysMenuService.listMenus(menu, accountService.getCurrentAccountId());
        return AjaxResult.success(menus);
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('bxy:menu:add')")
    @PostMapping
    public AjaxResult add(@RequestBody SysMenu menu) {
        if (MenuConstants.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(menu))) {
            throw new GeneralException(MenuCode.MENU_EXISTENCE);
//            return AjaxResult.error(ResourceUtil.transformMessageByLocale(MenuCode.MENU_EXISTENCE));
        } else if (MenuConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), MenuConstants.HTTP, MenuConstants.HTTPS)) {
            throw new GeneralException(MenuCode.ADDRESS_IS_HTTP_HTTPS);
        }
        menu.setCreateBy(accountService.getCurrentAccountId());
        menu.setCreateTime(new Date());
        return toAjax(sysMenuService.save(menu));
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId) {
        return AjaxResult.success(sysMenuService.getById(menuId));
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('bxy:menu:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody SysMenu menu) {
        if (MenuConstants.NOT_UNIQUE.equals(sysMenuService.checkMenuNameUnique(menu))) {
            throw new GeneralException(MenuCode.MENU_EXISTENCE);
        } else if (MenuConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), MenuConstants.HTTP, MenuConstants.HTTPS)) {
            throw new GeneralException(MenuCode.ADDRESS_IS_HTTP_HTTPS);
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            throw new GeneralException(MenuCode.IS_OWN);
        }
        menu.setUpdateBy(accountService.getCurrentAccountId());
        return toAjax(sysMenuService.updateById(menu));
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('bxy:menu:delete')")
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId) {
        if (sysMenuService.hasChildByMenuId(menuId)) {
            throw new GeneralException(MenuCode.DELEAT_NOT_ALLPWED);
        }
        if (sysRoleMenuService.checkMenuExistRole(menuId)) {
            throw new GeneralException(MenuCode.DELEAT_NOT_DISTRIBUTION);
        }
        return toAjax(sysMenuService.removeById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu) {
        List<SysMenu> menus = sysMenuService.listMenus(menu, accountService.getCurrentAccountId());
        return AjaxResult.success(sysMenuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysMenu> menus = sysMenuService.listMenus(new SysMenu(), accountService.getCurrentAccountId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", sysRoleMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", sysMenuService.buildMenuTreeSelect(menus));
        return ajax;
    }
}
